package spring.cloud.tasks.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import spring.cloud.tasks.executor.executor.Executor;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Configuration
public class BootStrap {
    //一台服务器只允许启动一个
    public static AtomicBoolean inited = new AtomicBoolean(false);
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    volatile Executor executor = null;

    @PostConstruct
    public void init() throws Exception {
        log.info("任务执行器挂载到项目...");
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                if (executor == null) {
                    try {
                        log.info("任务执行器启动开始");
                        buildAndStartExecutor();
                        log.info("任务执行器启动结束");
                    } catch (Exception e) {
                        log.info("任务执行器启动异常" + e.getMessage(), e);
                    }
                }
            }
        });

    }

    @PreDestroy
    public void destroy() throws Exception {
        log.info("任务执行器卸载...");
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("任务执行器销毁开始");
                    shutdown();
                    log.info("任务执行器销毁结束");
                } catch (Exception e) {
                    log.info("任务执行器销毁异常" + e.getMessage(), e);
                    e.printStackTrace();
                } finally {
                    executorService.shutdown();
                }
            }
        });

    }

    public void buildAndStartExecutor() throws Exception {
        /**
         * 一个服务器只能启动一个
         */
        if (!inited.compareAndSet(false, true)) {
            return;
        }
        String namespaceKey = "test";
        String executorId = UUID.randomUUID().toString();
        executor = new Executor(namespaceKey, executorId);
        executor.start();
    }

    public void shutdown() throws Exception {
        if (executor != null) {
            executor.stop();
        }
    }


}